<template>
  <div class="asset-type-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>资产类型管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加类型
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="类型名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入类型名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="启用" value="enabled" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 类型表格 -->
      <el-table
        :data="typeList"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="类型名称" min-width="150" />
        <el-table-column prop="code" label="类型代码" width="120" />
        <el-table-column prop="icon" label="图标" width="80">
          <template #default="{ row }">
            <el-icon :size="20">
              <component :is="iconComponents[row.icon]" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="100">
          <template #default="{ row }">
            <div class="color-preview" :style="{ backgroundColor: row.color }"></div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'enabled' ? 'success' : 'danger'">
              {{ row.status === 'enabled' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assetCount" label="资产数量" width="100" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="warning"
              size="small"
              @click="showEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button
              :type="row.status === 'enabled' ? 'danger' : 'success'"
              size="small"
              @click="toggleStatus(row)"
            >
              {{ row.status === 'enabled' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :disabled="row.assetCount > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑类型对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="类型代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入类型代码（英文）" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-select v-model="form.icon" placeholder="请选择图标" style="width: 100%">
            <el-option label="服务器" value="Monitor">
              <el-icon><component :is="iconComponents.Monitor" /></el-icon>
              服务器
            </el-option>
            <el-option label="网络设备" value="Connection">
              <el-icon><component :is="iconComponents.Connection" /></el-icon>
              网络设备
            </el-option>
            <el-option label="存储设备" value="FolderOpened">
              <el-icon><component :is="iconComponents.FolderOpened" /></el-icon>
              存储设备
            </el-option>
            <el-option label="安全设备" value="Lock">
              <el-icon><component :is="iconComponents.Lock" /></el-icon>
              安全设备
            </el-option>
            <el-option label="软件" value="Document">
              <el-icon><component :is="iconComponents.Document" /></el-icon>
              软件
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="form.color" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="enabled">启用</el-radio>
            <el-radio value="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入类型描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Monitor,
  Connection,
  FolderOpened,
  Lock,
  Document
} from '@element-plus/icons-vue'

// 注册图标组件
const iconComponents = {
  Plus,
  Search,
  Monitor,
  Connection,
  FolderOpened,
  Lock,
  Document
}

// 接口定义
interface AssetType {
  id: string
  name: string
  code: string
  icon: string
  color: string
  status: string
  assetCount: number
  description: string
  createTime: string
}

interface SearchForm {
  name: string
  status: string
}

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加类型')
const isEdit = ref(false)

// 搜索表单
const searchForm = reactive<SearchForm>({
  name: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 类型列表
const typeList = ref<AssetType[]>([])

// 表单数据
const form = reactive<AssetType>({
  id: '',
  name: '',
  code: '',
  icon: '',
  color: '#409eff',
  status: 'enabled',
  assetCount: 0,
  description: '',
  createTime: ''
})

// 表单引用
const formRef = ref()

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入类型名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入类型代码', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
      message: '类型代码必须以字母开头，只能包含字母、数字和下划线',
      trigger: 'blur'
    }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取类型列表
const getTypeList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    // 模拟数据
    const mockData: AssetType[] = [
      {
        id: 'TYPE001',
        name: '服务器',
        code: 'server',
        icon: 'Monitor',
        color: '#409eff',
        status: 'enabled',
        assetCount: 15,
        description: '各类服务器设备',
        createTime: '2024-01-15 10:30:00'
      },
      {
        id: 'TYPE002',
        name: '网络设备',
        code: 'network',
        icon: 'Connection',
        color: '#67c23a',
        status: 'enabled',
        assetCount: 8,
        description: '交换机、路由器等网络设备',
        createTime: '2024-01-16 14:20:00'
      },
      {
        id: 'TYPE003',
        name: '存储设备',
        code: 'storage',
        icon: 'FolderOpened',
        color: '#e6a23c',
        status: 'enabled',
        assetCount: 5,
        description: '存储阵列、磁盘等存储设备',
        createTime: '2024-01-17 09:15:00'
      },
      {
        id: 'TYPE004',
        name: '安全设备',
        code: 'security',
        icon: 'Lock',
        color: '#f56c6c',
        status: 'enabled',
        assetCount: 3,
        description: '防火墙、入侵检测等安全设备',
        createTime: '2024-01-18 16:45:00'
      },
      {
        id: 'TYPE005',
        name: '软件',
        code: 'software',
        icon: 'Document',
        color: '#909399',
        status: 'disabled',
        assetCount: 0,
        description: '各类软件资产',
        createTime: '2024-01-19 11:30:00'
      }
    ]

    typeList.value = mockData
    pagination.total = mockData.length

  } catch (error) {
    ElMessage.error('获取类型列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getTypeList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: ''
  })
  handleSearch()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加类型'
  isEdit.value = false
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row: AssetType) => {
  dialogTitle.value = '编辑类型'
  isEdit.value = true
  Object.assign(form, row)
  dialogVisible.value = true
}

// 切换状态
const toggleStatus = (row: AssetType) => {
  const newStatus = row.status === 'enabled' ? 'disabled' : 'enabled'
  const action = newStatus === 'enabled' ? '启用' : '禁用'

  ElMessageBox.confirm(
    `确定要${action}类型 "${row.name}" 吗？`,
    `确认${action}`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    row.status = newStatus
    ElMessage.success(`${action}成功`)
  }).catch(() => {
    ElMessage.info(`已取消${action}`)
  })
}

// 删除类型
const handleDelete = (row: AssetType) => {
  if (row.assetCount > 0) {
    ElMessage.warning('该类型下还有资产，无法删除')
    return
  }

  ElMessageBox.confirm(
    `确定要删除类型 "${row.name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = typeList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      typeList.value.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑逻辑
        const index = typeList.value.findIndex(item => item.id === form.id)
        if (index > -1) {
          typeList.value[index] = { ...form }
          ElMessage.success('编辑成功')
        }
      } else {
        // 添加逻辑
        const newType: AssetType = {
          ...form,
          id: `TYPE${String(Date.now()).slice(-6)}`,
          assetCount: 0,
          createTime: new Date().toLocaleString()
        }
        typeList.value.unshift(newType)
        pagination.total++
        ElMessage.success('添加成功')
      }
      dialogVisible.value = false
      resetForm()
    }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: '',
    name: '',
    code: '',
    icon: '',
    color: '#409eff',
    status: 'enabled',
    assetCount: 0,
    description: '',
    createTime: ''
  })
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  getTypeList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  getTypeList()
}

// 组件挂载时获取数据
onMounted(() => {
  getTypeList()
})
</script>

<style scoped>
.asset-type-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.02);
  border-radius: 8px;
  border: 1px solid rgba(120, 220, 255, 0.1);
}

.color-preview {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 表格样式优化 */
:deep(.el-table) {
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid rgba(120, 220, 255, 0.1);
}

:deep(.el-table__header) {
  background: rgba(120, 220, 255, 0.05);
}

:deep(.el-table th) {
  background: rgba(120, 220, 255, 0.05);
  border-color: rgba(120, 220, 255, 0.1);
  color: var(--tech-text-primary);
}

:deep(.el-table td) {
  border-color: rgba(120, 220, 255, 0.1);
  color: var(--tech-text-secondary);
}

:deep(.el-table__row:hover) {
  background: rgba(120, 220, 255, 0.05);
}

/* 对话框样式 */
:deep(.el-dialog) {
  background: rgba(15, 25, 40, 0.95);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(120, 220, 255, 0.2);
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid rgba(120, 220, 255, 0.1);
  padding-bottom: 15px;
}

:deep(.el-dialog__title) {
  color: var(--tech-text-primary);
  font-weight: 600;
}

/* 选择器选项样式 */
:deep(.el-select-dropdown) {
  background: rgba(15, 25, 40, 0.95);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(120, 220, 255, 0.2);
}

:deep(.el-select-dropdown__item) {
  color: var(--tech-text-secondary);
}

:deep(.el-select-dropdown__item:hover) {
  background: rgba(120, 220, 255, 0.1);
}

:deep(.el-select-dropdown__item.is-selected) {
  background: rgba(120, 220, 255, 0.2);
  color: var(--tech-accent-color);
}
</style>
